package com.hellowx.qydcdev.service.impl;

import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.hellowx.qydcdev.dao.GoodsCategoryDao;
import com.hellowx.qydcdev.dao.GoodsDao;
import com.hellowx.qydcdev.entity.Goods;
import com.hellowx.qydcdev.entity.GoodsCategory;
import com.hellowx.qydcdev.entity.User;
import com.hellowx.qydcdev.exception.CustomException;
import com.hellowx.qydcdev.exception.CustomExceptionType;
import com.hellowx.qydcdev.service.GoodsCategoryService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * Created on 2022/1/13.
 *
 * @author Hello WX
 */
@Service("goodsCategory")
public class GoodsCategoryServiceImpl implements GoodsCategoryService {

    @Resource
    private GoodsCategoryDao goodsCategoryDao;
    @Resource
    private GoodsDao goodsDao;

    @Override
    public List<GoodsCategory> selectList(HttpServletRequest request) {
        User loginUser = (User) request.getAttribute("loginUser");
        return new LambdaQueryChainWrapper<>(goodsCategoryDao)
                .eq(GoodsCategory::getBusinessId, loginUser.getBusinessId())
                .list();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String deleteNoGoods(Long categoryId) {
        List<Goods> list = new LambdaQueryChainWrapper<>(goodsDao)
                .eq(Goods::getCategoryId, categoryId)
                .list();
        if (list!=null && list.size()>0){
            throw new CustomException(CustomExceptionType.USER_INPUT_EXCEPTION,"请先删除该分类下的商品");
        }
        int rows = goodsCategoryDao.deleteById(categoryId);
        return rows>0 ? "删除成功!" : "删除失败";
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String addCategory(String name, HttpServletRequest request) {
        User loginUser = (User) request.getAttribute("loginUser");
        GoodsCategory goodsCategory = new GoodsCategory();
        goodsCategory.setName(name);
        goodsCategory.setBusinessId(loginUser.getBusinessId());
        int rows = goodsCategoryDao.insert(goodsCategory);
        return rows>0 ? "新增成功" : "新增失败";
    }
}
